/**
 * Created by Egan on 2015/1/16.
 */

class GameApp extends egret.DisplayObjectContainer{

    /**
     * 加载进度界面
     */
    private loadingView:LoadingUI;

    public constructor(){
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE,this.onAddToStage,this);
    }

    private onAddToStage(event:egret.Event){
        //设置加载进度界面
        this.loadingView  = new LoadingUI();
        this.stage.addChild(this.loadingView);

        //初始化Resource资源加载库
        RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE,this.onConfigComplete,this);
        RES.loadConfig("resource/resource.json","resource/");
    }

    /**
     * 配置文件加载完成,开始预加载preload资源组。
     * @param event
     */
    private onConfigComplete(event:RES.ResourceEvent):void{
//        console.log("配置文件加载完成");
        RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE,this.onConfigComplete,this);
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE,this.onResourceLoadComplete,this);
        RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS,this.onResourceProgress,this);
        RES.loadGroup("preload");
    }

    /**
     * preload资源组加载完成
     * @param event
     */
    private onResourceLoadComplete(event:RES.ResourceEvent):void{
        if(event.groupName=="preload"){
            this.stage.removeChild(this.loadingView);
            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE,this.onResourceLoadComplete,this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS,this.onResourceProgress,this);
            this.createGameScene();
        }
    }

    /**
     * preload资源组加载进度
     */
    private onResourceProgress(event:RES.ResourceEvent):void{
        if(event.groupName=="preload"){
            this.loadingView.setProgress(event.itemsLoaded,event.itemsTotal);
        }
    }

    private createGameScene():void{
        var sky:egret.Bitmap=this.createBitmapByName("bgImage");
        this.addChild(sky);
        var stageW:number=this.stage.stageWidth;
        var stageH:number=this.stage.stageHeight;
        sky.width=stageW;
        sky.height=stageH;

        var egret_txt:egret.Bitmap=this.createBitmapByName("egret_txt");
        egret_txt.x=(stageW-egret_txt.width)/2;
        egret_txt.y=stageH-30;
        this.addChild(egret_txt);

        //游戏主类
        var gameContainer:catgame.GameContainer=new catgame.GameContainer();
        this.addChild(gameContainer);

        //FPS
        egret.Profiler.getInstance().run();
    }

    /**
     * 与resource.json里面配置的name一致
     * @param name
     * @returns {egret.Bitmap}
     */
    private createBitmapByName(name:string):egret.Bitmap{
        var result:egret.Bitmap=new egret.Bitmap();
        var texture:egret.Texture=RES.getRes(name);
        result.texture=texture;

        return result;
    }



}

